package com.anyou.web.controller.system;

import java.util.List;
import java.util.Set;
import java.util.UUID;

import com.anyou.mall.tencentim.UserSignUtils;
import com.anyou.mall.tencentim.UserVo;
import com.anyou.mall.use.domain.User;
import com.anyou.mall.use.service.IUserService;
import com.anyou.system.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.anyou.common.constant.Constants;
import com.anyou.common.core.domain.AjaxResult;
import com.anyou.common.core.domain.entity.SysMenu;
import com.anyou.common.core.domain.entity.SysUser;
import com.anyou.common.core.domain.model.LoginBody;
import com.anyou.common.utils.SecurityUtils;
import com.anyou.framework.web.service.SysLoginService;
import com.anyou.framework.web.service.SysPermissionService;
import com.anyou.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
@Api(tags = "用户登录")
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IUserService userService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // security登录校验，并生成token
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
//        //新md5登录校验，并生成token
//        String token= loginService.login2(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
//                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        SysUser one = sysUserService.getOne(new QueryWrapper<SysUser>().lambda()
                .eq(SysUser::getUserName, loginBody.getUsername()));
        String userSign="";
        String miniUserId="";
        String userType="";
        String carPartsShopId="";
        String sysUserId="";
        if(one!=null){
            userType=one.getUserType();
            sysUserId=one.getUserId().toString();
            if(one.getMiniUserId()!=null){
                userSign = UserSignUtils.genSig(one.getMiniUserId().toString(), 604800);
                miniUserId=one.getMiniUserId().toString();
                carPartsShopId=one.getCarPartsShopId().toString();
            }
            if(userType.equals("00")){
                //查询小程序端的超管用户
                User admin = userService.getOne(new LambdaQueryWrapper<User>()
                        .eq(User::getPhoneNumber, "admin"));
                if(admin==null){
                    User user = new User();
                    user.setPhoneNumber("admin");
                    user.setLoginPassword("e10adc3949ba59abbe56e057f20f883e");
                    user.setNickName("后台超级管理员");
                    boolean save = userService.save(user);
                    miniUserId=user.getUserId().toString();
                    userSign=UserSignUtils.genSig(user.getUserId().toString(), 604800);
                }else{
                    miniUserId=admin.getUserId().toString();
                    userSign=UserSignUtils.genSig(admin.getUserId().toString(), 604800);
                }
            }
        }
        ajax.put("userSign",userSign);
        ajax.put("miniUserId",miniUserId);
        ajax.put("userType",userType);
        ajax.put("sysUserId",sysUserId);
        ajax.put("carPartsShopId",carPartsShopId);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
